<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <title>音频流</title>
    <style>
        .button {
            background-color: #4CAF50;
            /* 绿色背景 */
            color: white;
            /* 白色文字 */
            padding: 15px 32px;
            /* 内边距 */
            text-align: center;
            /* 文字居中 */
            text-decoration: none;
            /* 去掉下划线 */
            display: inline-block;
            /* 行内块元素 */
            font-size: 16px;
            /* 字体大小 */
            margin: 4px 2px;
            /* 外边距 */
            cursor: pointer;
            /* 鼠标悬停时显示为手型 */
            border-radius: 4px;
            /* 圆角边框 */
            border: none;
            /* 去掉边框 */
        }

        /* 定义鼠标悬停时按钮的样式 */
        .button:hover {
            background-color: #45a049;
            /* 更深的绿色背景 */
        }
    </style>
</head>

<body>
    <h1>音频流测试</h1>
    <button  class="button" id="playBtn">开始播放(移动设备若没有声音，请尝试点击)</button>
    <script>
        let audioContext;
        let audioSource;
        const CHANNELS = 1;
        const RATE = 16000;
        const CHUNK = 512;
        const ws = new WebSocket('ws://' + window.location.hostname+':8765/ws');


        function playAudio(data) {
            if (!audioContext) {
                audioContext = new (window.AudioContext || window.webkitAudioContext)();
            }

            if (audioSource) {
                audioSource.disconnect();
            }

            const audioBuffer = audioContext.createBuffer(CHANNELS, CHUNK, RATE);
            const channelData = audioBuffer.getChannelData(0);
            for (let i = 0; i < CHUNK; i++) {
                // 将 int16 转换为 float32，范围 [-1.0, 1.0]
                channelData[i] = data[i] / 32768.0;
            }

            audioSource = audioContext.createBufferSource();
            audioSource.buffer = audioBuffer;
            audioSource.connect(audioContext.destination);
            audioSource.start(0);
        }

        ws.binaryType = 'arraybuffer'; // 确保接收二进制数据

        ws.onmessage = function (event) {
            const audioData = new Int16Array(event.data);
            playAudio(audioData);
        };

        ws.onerror = function (error) {
            console.error('WebSocket 错误:', error);
        };

        ws.onclose = function () {
            console.log('WebSocket 连接已关闭');
        };
        document.getElementById('playBtn').addEventListener('click', function () {
            audioSource.start(0);
        });
    </script>
</body>

</html>